package controllers;

import java.util.ArrayList;
import java.util.List;

import models.Instructor;
import models.Student;
import others._;
import play.data.validation.Required;
import play.data.validation.Validation;
import play.mvc.Controller;

/**
 * Guests controller.
 * <p>
 * Handles
 * <ul>
 * <li>Registration
 * <li>TODO Forgot password
 * </ul>
 * 
 * @author mahmoudsakr
 */
public class Guests extends Controller {
	public static void register() {
		List<Integer> dashes = new ArrayList<Integer>();

		int year = Integer.parseInt(_.now("yyyy")), month = Integer.parseInt(_.now("M"));

		// i starts from max possible XX-, and goes down to 1-
		for (int i = 1 + 3 * ((month >= 7 ? year : year - 1) - 2003); i > 0; i -= 3) {
			dashes.add(i);
		}

		render(dashes);
	}

	public static void doRegister(long dash, long stid, @Required (message = "You must enter a username") String username) throws Throwable {
		validation.email(username + "@student.guc.edu.eg");

		Student stu = Student.find("byUsername", username).first();
		Instructor ins = Instructor.find("byUsername", username).first();

		if (stu != null || ins != null) {
			Validation.addError(username, "That username is already registered");
		}

		if (stid == 0) {
			Validation.addError("" + stid, "Id missing");
		}

		if (dash == 0) {
			Validation.addError("" + dash, "Group missing");
		}

		if (Validation.hasErrors()) {
			Validation.keep();
			params.flash();
			register();
		}

		new Student(username, dash + "-" + stid).save();
		flash.success("You have successfully registered. Login with the password emailed to you.");
		Secure.login();
	}

}
